package com.woniuxy.realm;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.woniuxy.pojo.User;
import com.woniuxy.service.UserService;

import lombok.Data;
@Data
public class UserRealm extends AuthorizingRealm{
	@Resource
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("正在从数据库查询当前用户的角色/权限");
		//得到账号
		String account = (String) principals.getPrimaryPrincipal();
		//用于存放从数据库中查询出当前用户有哪些角色
		Set<String>roles = new HashSet<>();
		String ustate = userService.findUserByAccount(account).getUstate();
		System.out.println("============"+ustate);
		roles.add(ustate);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
		return info;
	}

	
	//认证的方法：从数据库中查询当前用户的信息（账号密码等）
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//获取用户提交的账号
		String account = (String) token.getPrincipal();
		//获取密码
		String pwd = new String((char[])token.getCredentials());
		System.out.println(pwd);
		//假设通过账号从数据库查询出数据
		User resultUser = userService.findUserByAccount(account);
		if (resultUser==null) {
			//账号不存在
			return null;
		}
		SimpleAuthenticationInfo info = 
			new SimpleAuthenticationInfo(
					resultUser.getAccount(), 
					resultUser.getPass(),
					getName());
		return info;
	}

}
